package com.tg.message.msg;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.appbase.custom.config.TGConfig;
import com.appbase.custom.constant.DeviceStateConstants;
import com.appbase.custom.constant.EventConstants;
import com.tange.core.backend.service.response.RxResponse;
import com.tange.feature.device.query.DeviceQuery;
import com.tange.base.toolkit.StringUtils;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.business.IMessageModule;
import com.tg.appcommon.router.TGBusiness;
import com.tg.data.bean.DeviceItem;
import com.tg.data.bean.DeviceSettingsInfo;
import com.tg.data.bean.DeviceSettingsInfo_;
import com.tg.data.helper.DeviceItemHelper;
import com.tg.data.helper.DeviceTypeHelper;
import com.tg.data.helper.DeviceTypeStorage;
import com.tg.data.http.entity.MessageDataBean;
import com.tg.message.R;

import io.objectbox.Box;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

/**
 * 消息详情页的初始信息
 */
public class MessageDataHolder {

    private static final String TAG = MessagePlayActivity.TAG_PLAY + "MessageDataHolder";

    public static final int MSG_EVENT_TYPE_TEXT = 100;
    public static final int MSG_EVENT_TYPE_VIDEO = 200;
    public static final int MSG_EVENT_TYPE_MAP = 300;
    public static final int MSG_EVENT_TYPE_AI = 400;

    public static final String EXT_PUSH_ORIGIN = "ext_push_orgin";
    public static final String EXT_DEVICE = "EXT_DEVICE";
    public static final int PUSH_ORIGIN_JPUSH = 0x01;

    private int displayType = MSG_EVENT_TYPE_TEXT;

    private MessageDataBean.ItemsBean eventMessage;
    private String desKey;

    private int origin = 0;

    private DeviceItem mDeviceItem;
    private DeviceSettingsInfo mDeviceSettingsInfo;

    private boolean canLive = false;

    private Context context;

    private int rotation = 0;

    private final Handler mainHandler = new Handler(Looper.getMainLooper());

    public MessageDataHolder(Context context) {
        this.context = context;
    }

    public int getDisplayType() {
        return displayType;
    }

    public boolean isPay() {
        return eventMessage.getIs_pay() == 1;
    }

    /**
     * 标识 当前消息 是否有 视频需要下载
     * TODO: 需要根据后台字段识别
     * @return
     */
    public boolean shouldDownloadVideo() {
        return isPay();
    }

    public MessageDataBean.ItemsBean getEventMessage() {
        return eventMessage;
    }
    public void setEventMessage(MessageDataBean.ItemsBean itemsBean){
        eventMessage = itemsBean;
    }

    public String getDesKey() {
        return desKey;
    }

    public DeviceItem getDeviceItem() {
        return mDeviceItem;
    }



    public DeviceSettingsInfo getDeviceSettingsInfo() {
        return mDeviceSettingsInfo;
    }



    private boolean isIPCDevice(String category){
        return !StringUtils.isEmpty(category) && category.toLowerCase().contains("ipc");
    }

    public void init(Intent intent, final Runnable onInitSuccessRunnable) {

        origin = intent.getIntExtra(EXT_PUSH_ORIGIN, 0);
        desKey = intent.getStringExtra(IMessageModule.EXT_DEVICE_DES);

        eventMessage = intent.getParcelableExtra(IMessageModule.EXT_EVENT_MESSAGE);
        mDeviceItem = intent.getParcelableExtra(EXT_DEVICE);
        if (eventMessage==null)return;
        rotation = DeviceTypeStorage.readDeviceRotation(context, eventMessage.getUuid());

        boolean hasAiService = DeviceTypeStorage.readAI(context, eventMessage.getUuid());

        displayType = MSG_EVENT_TYPE_TEXT;

        TGLog.i(TAG, "init: origin = " + origin);
        TGLog.i(TAG, "init: isPay = " + isPay());
        TGLog.i(TAG, "init: desKey = " + desKey);
        TGLog.i(TAG, "init: eventMessage = " + eventMessage);
        TGLog.i(TAG, "init: rotation = " + rotation);
        TGLog.i(TAG, "init: mDeviceItem = " + mDeviceItem);
        TGLog.i(TAG, "init: hasAiService = " + hasAiService);


        if (eventMessage.isIs_ai_tag() && !hasAiService && isIPCDevice(eventMessage.getCategory())) { // 没有AI服务，但是这条是AI事件，意味着是限时推送
            displayType = MSG_EVENT_TYPE_AI;
        } else if (TextUtils.isEmpty(eventMessage.getImage_path()) ||
                MessageDisplayMapping.isNoMediaEvent(eventMessage.getTag()) || TextUtils.equals(eventMessage.getMessage_type(), EventConstants.NOTICE)) {
            displayType = MSG_EVENT_TYPE_TEXT;
        } else if (!TextUtils.isEmpty(eventMessage.getPos())) {
            displayType = MSG_EVENT_TYPE_MAP;
        } else if (isPay()) {
            displayType = MSG_EVENT_TYPE_VIDEO;
        } else {
            displayType = MSG_EVENT_TYPE_VIDEO;
        }

        TGLog.i(TAG, "init: displayType = " + displayType);

        Box<DeviceSettingsInfo> deviceSettingsInfoBox = (Box<DeviceSettingsInfo>) TGBusiness.getMessageModule().getDeviceSettingsInfo();

        try {
            mDeviceSettingsInfo = deviceSettingsInfoBox.query().equal(DeviceSettingsInfo_.uuid, eventMessage.getUuid()).build().findFirst();
        } catch (Throwable ex) {
            // ignore
        }

        if (mDeviceSettingsInfo == null) {
            mDeviceSettingsInfo = new DeviceSettingsInfo();
        }

        getCameraInfo(onInitSuccessRunnable);
    }

    /**
     * 是否展示 "查看完整录像" 的入口
     */
    public boolean shouldShowFullVideoEntry() {
        if (mDeviceItem == null) {
            return false;
        }

        // 门锁不展示
        if (isLockBellMessage()) {
            return false;
        }

        // 门铃不展示
        boolean isPassiveDoorbell = mDeviceItem == null ? false : DeviceTypeHelper.isPassiveDoorBellDevice(mDeviceItem.device_type);
        if (isPassiveDoorbell) {
            return false;
        }

        return true;
    }

    public boolean isLockBellMessage() {
        if (mDeviceItem != null) {
            // 台灯走的 MediaSync2
            if (DeviceTypeHelper.isLamp(mDeviceItem.device_type)) {
                return false;
            }
        }

        if (mDeviceItem != null && DeviceTypeHelper.isLockBell(mDeviceItem.device_type)) {
            return true;
        }

        return eventMessage != null && (TextUtils.equals(eventMessage.getTag(), EventConstants.LOCK_ABNORMAL) ||
                TextUtils.equals(eventMessage.getTag(), EventConstants.LOCK_ALARM) ||
                TextUtils.equals(eventMessage.getTag(), EventConstants.DOORBELL_CALL));
    }

    /**
     * 设备是否在线
     * @return
     */
    public boolean isDeviceOnline() {
        return mDeviceItem != null && mDeviceItem.is_online == DeviceStateConstants.DEVICE_ONLINE;
    }

    /**
     * 针对Wifi设备，若无云服务，且在线的时候，可展示底部广告位
     * @return
     */
    public boolean shouldShowCloudServiceAd() {
        if (mDeviceItem == null) {
            return false;
        }
        if (mDeviceItem.isLamp()) {
            return false;
        }
        if (mDeviceItem.isCar()) {
            return false;
        } else if (mDeviceItem.is4GDevice()) {
            return false;
        } else if (mDeviceItem.device_type != null && DeviceTypeHelper.isLockBell(mDeviceItem.device_type) &&
                (isContains(mDeviceItem.attrs, "service", "audio-pic") || isContains(mDeviceItem.attrs, "service", "only-pic"))){
            return false;
        } else if (mDeviceItem.device_type != null && DeviceTypeHelper.isBirdFeeder(mDeviceItem.device_type)){
            return mDeviceItem.ai_server_data == null;
        }
        else {
            if (!isDeviceOnline()) {
                return false;
            }
            if (mDeviceItem.server_data != null) {
                return false;
            }

            return true;
        }
    }

    public static boolean isContains(String attr, String key, String val){
        if (StringUtils.isEmpty(attr)){
            return false;
        }
        JSONObject jsonObject = JSONObject.parseObject(attr);
        if (jsonObject != null){
            String power = jsonObject.getString(key);
            return StringUtils.equalsIgnoreCase(power, val);
        }
        return false;
    }

    public boolean noDeviceInfo() {
        if (eventMessage == null) return true;
        return "0".equals(eventMessage.getDevice_id()) || TextUtils.isEmpty(eventMessage.getDevice_id());
    }

    private void getCameraInfo(final Runnable onInitSuccessRunnable) {

        if (noDeviceInfo()) {
            TGLog.i(TAG, "[getCameraInfo] skip request, no device id");
            if (onInitSuccessRunnable != null) {
                mainHandler.post(onInitSuccessRunnable);
            }
            return;
        }

        if (mDeviceItem != null && !TextUtils.isEmpty(mDeviceItem.device_type)) {
            TGLog.i(TAG, "[getCameraInfo] skip request");
            updateSettingInfo();
            if (onInitSuccessRunnable != null) {
                mainHandler.post(onInitSuccessRunnable);
            }
            return;
        }

        DeviceQuery.INSTANCE.querySingleFull(eventMessage.getUuid())
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<RxResponse<DeviceItem>>() {
                    @Override
                    public void onSubscribe(Disposable d) {}

                    @Override
                    public void onNext(RxResponse<DeviceItem> rxResult) {
                        if (rxResult == null || !rxResult.isSuccess) {
                            return;
                        }

                        mDeviceItem = rxResult.content;
                        updateSettingInfo();
                        TGLog.i(TAG, "getCameraInfo onSuccess: desKey = " + desKey);
                        if (onInitSuccessRunnable != null) {
                            mainHandler.post(onInitSuccessRunnable);
                        }
                    }


                    @Override
                    public void onError(Throwable e) {
                        TGLog.i(TAG, "[onError] ");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
    private void updateSettingInfo(){
        if (mDeviceItem != null && mDeviceSettingsInfo != null) {
            mDeviceSettingsInfo.deviceID = mDeviceItem.id;
            mDeviceSettingsInfo.uuid = mDeviceItem.uuid;
            mDeviceSettingsInfo.online = (mDeviceItem.is_online == DeviceStateConstants.DEVICE_ONLINE);
            mDeviceSettingsInfo.firmware_id = mDeviceItem.firmware_id;
            mDeviceSettingsInfo.timezone = mDeviceItem.timezone;
            mDeviceSettingsInfo.deviceStatus = mDeviceItem.is_open;
            if (DeviceItemHelper.isCar(mDeviceItem)) {
                if (mDeviceSettingsInfo != null) {
                    mDeviceSettingsInfo.isCar = true;
                }
            }
            desKey = mDeviceItem.des_key;

            TGLog.i(TAG, " update: desKey = " + desKey);
        }
    }
    public void finishPage(Activity activity) {
        if (activity == null) return;

        Intent intent = new Intent();
        intent.putExtra(IMessageModule.EXT_EVENT_MESSAGE, eventMessage);
        activity.setResult(Activity.RESULT_OK, intent);
        activity.finish();
        if (origin == PUSH_ORIGIN_JPUSH) {
            activity.overridePendingTransition(0, R.anim.push_botton_out);
        }
    }

}
